package cn.school.web;

import cn.school.entity.Page;
import cn.school.entity.Student;
import cn.school.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@Controller
//@RestController
@RequestMapping("student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    //web对象
    //请求参数
    //@RequestMapping("")
    @GetMapping("search")
    //@PostMapping("")
    public ModelAndView search(@RequestParam(name = "pageNo",defaultValue = "1") int pageNo, @RequestParam(name = "pageSize",defaultValue = "10") int pageSize,@ModelAttribute("sname") String sname, String qq, String telephone, HttpServletRequest request){
        Page<Student> p = this.studentService.search(pageNo, pageSize, sname, qq, telephone, null, null);
        request.setAttribute("p",p);
        //return "/WEB-INF/jsp/student.jsp";//视图地址

        ModelAndView mv=new ModelAndView();
        //mv.setViewName("/WEB-INF/jsp/student.jsp");
        mv.setViewName("student");
        mv.addObject("p",p);
        return mv;
    }
    @GetMapping("/toAdd")
    public String toAdd(){
        return "addstudent";
    }
    @PostMapping("add")
    public String add(Student stu,@RequestParam(name = "idcardpic2",required = false) MultipartFile idcard,HttpServletRequest request) {
        if(idcard.isEmpty()==false){
            String filename = idcard.getOriginalFilename();
            String suffix=filename.substring(filename.lastIndexOf('.'));
            String newName= UUID.randomUUID()+suffix;
            ServletContext app = request.getServletContext();
            String images = app.getRealPath("images");
            File f=new File(images);
            if(f.exists()==false)
                f.mkdirs();
            try {
                idcard.transferTo(new File(f,newName));
                stu.setIdcardpic(newName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        int add = studentService.add(stu);
        if(add>0)
            return "redirect:/student/search";

        //return "/WEB-INF/jsp/addstudent.jsp";
        return "addstudent";
    }
    @InitBinder
    public  void initDate(WebDataBinder web){
        web.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
    }
}
